﻿<%@ WebHandler Language="C#" Class="BomRquestCancelPageHandler" %>

/* Description:配套单撤销管理后端接口
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan 
 * create Date:2025.10.15
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Data;
using System.Text;
using BusinessRule.DTO;
using DatabaseAccess.DBUtility;
using System.Web.SessionState;
using Newtonsoft.Json;
using System.Collections;
using System.IO;
using System.Configuration;

public class BomRquestCancelPageHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo = new CurrentUserInfo();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "getUserInfo":
                    getUserInfo(context);
                    break;
                case "getData":
                    getData(context);
                    break;
                case "saveCancleData":
                    saveCancleData(context);//保存撤销
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(result));
        }
    }

    //生成查询sql
    string getQuerySql(HttpContext context)
    {
        string sql = @"
SELECT t.id,t.ismeshandle,t.isuse,t.methodname,e.fullname,t.createdate,e2.fullname cancleemp,t.lastchangedate,
       cci.mfgordername,cci.togetherflag,cci.containerid,cci.containername,cci.productname,cci.productdescription,cci.qty,
       cci.workflowname || ':' || cci.workflowrevision workflowinfo,
       DECODE(cci.containertype,'2','批量加工','3','批量带子序号',7,'单件加工') containertype,cci.plannedstartdate,cci.plannedcompletiondate,
       ws.workflowstepname,aps.apsplandetailid
FROM sync_sendto_wms t
INNER JOIN apsplandetail aps ON aps.apsplandetailid = t.uniquecolvalue
INNER JOIN containercurrentinfo cci ON cci.containerid = aps.containerid
LEFT JOIN workflowstep ws ON ws.workflowstepid = aps.workflowstepid
LEFT JOIN employee e ON e.employeeid = t.create_emp
LEFT JOIN employee e2 ON e2.employeeid = t.lastchange_emp
WHERE t.ismeshandle = 1 AND t.methodname = '配套单下发'";
        //主制分厂
        if (context.Request["factoryid"] != null && context.Request["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", context.Request["factoryid"].ToString());
        }

        //件号
        if (context.Request["productname"] != null && context.Request["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname LIKE '%{0}%'", context.Request["productname"].ToString());
        }

        //订单号
        if (context.Request["mfgordername"] != null && context.Request["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername LIKE '%{0}%'", context.Request["mfgordername"].ToString());
        }

        //批次号
        if (context.Request["containername"] != null && context.Request["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername LIKE '%{0}%'", context.Request["containername"].ToString());
        }

        //状态
        if (context.Request["isuse"] != null && context.Request["isuse"].ToString() != "")
        {
            sql += string.Format(" AND t.isuse = '{0}'", context.Request["isuse"].ToString());
        }
        return sql;
    }

    void getUserInfo(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", ReturnData = m_UserInfo }));
        }
    }

    void getData(HttpContext context)
    {
        string sql = getQuerySql(context);
        uMESPagingDataDTO paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(context.Request.Form["pageNumber"].ToString());//页码
        paraPage.PageSize = Convert.ToInt32(context.Request.Form["PageSize"].ToString());//每页页数
        paraPage.strSQL = sql;
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(paraPage);
        foreach (DataColumn col in result.DBTable.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    void saveCancleData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
            return;
        }
        string ToAppID_WMS = ConfigurationManager.AppSettings["ToAppID_WMS"].ToString();
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["postData"].ToString());
        ArrayList sqlList = new ArrayList();
        foreach (DataRow dr in dtPostData.Rows)
        {
            Dictionary<string, string> para = new Dictionary<string, string>();
            para["bizDataNo"] = dr["mfgordername"].ToString();//生产订单号
            para["docNo"] = "";//业务流水号
            para["batchNum"] = dr["containername"].ToString();//批次号
            para["status"] = "撤销出库";
            string json = JsonConvert.SerializeObject(para);
            
            string insertSql = @"
INSERT INTO sync_sendto_wms(methodname,json,toappid,tablename,uniquecolname,uniquecolvalue,create_emp)
VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}')";
            
            insertSql = string.Format(insertSql,
                "配套单撤销",
                json,
                ToAppID_WMS,
                "apsplandetail",
                "apsplandetailid",
                dr["apsplandetailid"].ToString(),
                m_UserInfo.EmployeeID
            );
            sqlList.Add(insertSql);

            string updateSql = @"UPDATE sync_sendto_wms t SET t.isuse = 1,t.lastchange_emp = '{0}',t.lastchangedate = sysdate WHERE t.id = '{1}'";
            updateSql = string.Format(updateSql, m_UserInfo.EmployeeID, dr["id"].ToString());
            sqlList.Add(updateSql);
        }
        Boolean isSuccess = DatabaseHelper.ExecuteSqlListTran(sqlList);
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = isSuccess, Message = "", DBTable = null }));
    }
}